package com.atguigu.async;

import com.atguigu.exception.SleepUtils;

import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

public class FutureDemo02 {
    public static void main(String[] args) throws Exception {
        //thenAcceptSerial();
        //thenApplySerial();
        //thenAcceptParallel();
        thenAcceptSerial1();
    }

    //发起一个异步请求 并行执行
    private static void thenAcceptParallel() {
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println("你好supplyAsync");
            return 1024;
        });
        //第一个线程睡眠5s 第二个睡眠1s 按理第二应该等第一个执行完之后再执行 说明此时采用了并行的方式
        futureA.thenAcceptAsync((Integer acceptVal)->{
            SleepUtils.sleep(5);
            System.out.println("第一个线程thenAcceptAsync拿到值"+acceptVal);
        },MyExecutor.getInstance());

        futureA.thenAcceptAsync((Integer acceptVal)->{
            SleepUtils.sleep(1);
            System.out.println("第二个线程thenAcceptAsync拿到值"+acceptVal);
        },MyExecutor.getInstance());
    }

    //发起一个异步请求 串行执行
    private static void thenAcceptSerial1() {
        CompletableFuture<Integer> supplyFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("你好supplyAsync");
            return 1024;
        });
        supplyFuture.thenAccept((Integer acceptVal)->{
            SleepUtils.sleep(5);
            System.out.println("第一个线程thenAccept拿到值"+acceptVal);
        });
        supplyFuture.thenAccept((Integer acceptVal)->{
            SleepUtils.sleep(1);
            System.out.println("第二个线程thenAccept拿到值"+acceptVal);
        });
    }












    //发起一个异步请求 串行执行
    private static void thenAcceptSerial() {
        CompletableFuture<Void> supplyFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("你好supplyAsync");
            return 1024;
        }).thenAccept((Integer acceptVal)->{
            System.out.println("thenAccept拿到值"+acceptVal);
        });
    }
    //发起一个异步请求 串行执行
    private static void thenApplySerial() throws Exception {
        CompletableFuture<Integer> supplyFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("你好supplyAsync");
            return 1024;
        }).thenApply((Function<Integer,Integer>) acceptVal->{
            System.out.println("thenApply拿到值"+acceptVal);
            return 2048;
        });
    }
}
